<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Common\Repositories\System;

use App\Common\Dao\System\CustomerJobsDao;
use App\Common\Repositories\BaseRepository;
use App\Exception\AppException;
use Hyperf\DbConnection\Db;
use xsl\enums\Code;
use xsl\enums\Status;

class CustomerJobsRepository extends BaseRepository
{
    public function __construct(CustomerJobsDao $dao)
    {
        $this->dao = $dao;
    }

    public function getWhereList(array $fields = ['*'], array $where = [])
    {
        $query = $this->dao->search($where)->select($fields);
        return $query->orderBy('id', 'desc')->get();
    }

    public function toggleBy($id, string $field = 'status'){
        $model = $this->dao->get($id);
        $status = $model->$field == Status::ENABLE ? Status::DISABLE : Status::ENABLE;
        Db::beginTransaction();
        try{
            $update = [$field => $status];
            $this->dao->update(intval($id), $update);
            Db::commit();
        } catch(\Throwable $ex){
            Db::rollBack();
            throw new AppException($ex->getMessage(), Code::ERROR);
        }
        return true;
    }
}
